import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:dio/dio.dart';

import 'package:family_app/src/features/gallery/models/photo_group_model.dart';
import 'package:family_app/src/features/gallery/models/photo_model.dart';

/// 相册照片分组列表提供者（按日期分组）
final photoGroupsProvider = FutureProvider.family<List<PhotoGroupModel>, String>(
  (ref, albumId) async {
    try {
      // 创建专门用于相册API的Dio实例
      final dio = Dio(BaseOptions(
        baseUrl: 'http://10.0.2.2:9092',
        connectTimeout: const Duration(seconds: 5),
        receiveTimeout: const Duration(seconds: 10),
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
        },
      ));
      
      // 添加日志拦截器，方便调试
      dio.interceptors.add(LogInterceptor(
        requestBody: true,
        responseBody: true,
      ));
      
      // 调用照片列表接口
      final response = await dio.get('/photo/list', queryParameters: {
        'albumId': albumId,
      });
      
      // 处理响应
      if (response.statusCode == 200 && response.data != null) {
        final responseData = response.data;
        
        // 检查接口返回的状态码
        if (responseData['code'] == '200' && responseData['data'] != null) {
          final List<dynamic> groupsData = responseData['data'];
          
          // 将接口返回的数据转换为PhotoGroupModel列表
          return groupsData.map((groupData) => PhotoGroupModel.fromJson(groupData)).toList();
        }
      }
      
      // 如果接口调用失败或响应格式不正确，返回空列表
      return [];
    } catch (e) {
      print('获取照片分组列表异常: $e');
      return [];
    }
  },
);

/// 从照片分组列表中提取所有照片（扁平化列表）
final flattenedPhotosProvider = Provider.family<List<PhotoModel>, List<PhotoGroupModel>>(
  (ref, photoGroups) {
    final List<PhotoModel> allPhotos = [];
    
    for (final group in photoGroups) {
      allPhotos.addAll(group.photos);
    }
    
    return allPhotos;
  },
);
